import store from '@/store';
import settings from "@/config/settings";

//檢查小程序更新
export function mpUpData() {
	//新版本更新
	if (uni.canIUse('getUpdateManager')) {
		//判断当前微信版本是否支持版本更新
		const updateManager = uni.getUpdateManager();
		updateManager.onCheckForUpdate(function(res) {
			if (res.hasUpdate) {
				console.log(res.hasUpdate)
				// 请求完新版本信息的回调
				updateManager.onUpdateReady(function() {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，将重启应用？',
						showCancel: false,
						success: function(res) {
							if (res.confirm) {
								// 重启清除本地缓存
								uni.clearStorage();
								// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								updateManager.applyUpdate();
							}
						},
					});
				});
				updateManager.onUpdateFailed(function() {
					uni.showModal({
						// 新的版本下载失败
						title: '已经有新版本了哟~',
						content: '新版本已经上线啦~，请您删除当前小程序，重新搜索打开哟~',
					});
				});
			} else {}
		});
	} else {
		uni.showModal({
			title: '提示',
			content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
		});
	}
}
// 获取系统导航高度
export function systemInfo() {
	uni.getSystemInfo({
		success: (e) => {
			// console.log(e, '=====系统信息')
			let statusBar = 0;
			let customBar = 0;
			let tabbarH = 0;
			let tabbarPaddingB = 0;
			statusBar = e.statusBarHeight;
			// #ifdef MP-WEIXIN
			const custom = wx.getMenuButtonBoundingClientRect();
			if (custom && custom.bottom) {
				customBar = custom.bottom + custom.top - e.statusBarHeight;
			}
			// #endif
			let modelArr = ['X', 'XR', 'XS', '11', '12', '13', '14', '15', '16'];
			let model = e.model;
			model && modelArr.forEach(item => {
				//适配iphoneX以上的底部，给tabbar一定高度的padding-bottom
				if (model.indexOf(item) != -1 && model.indexOf('iPhone') != -1) {
					tabbarH = 70
					tabbarPaddingB = 25
				}
			})
			store.commit('setSystemInfo', {
				...e,
				...{
					statusBar,
					customBar,
					tabbarH,
					tabbarPaddingB
				}
			})
		}
	})
}


/*
 * 获取定位信息
 */
export function getLocation(successCallback) {

	uni.authorize({
		scope: 'scope.userLocation',
		success(res) {
			setLocationMap((locate) => {
				successCallback && successCallback(locate)
			})
		},
		fail(err) {
			store.commit('setLocateInformation', {});
			// 如果用户位置信息没有，则弹出确认框  GPS授权
			uni.showModal({
				content: '请自行在小程序设置中授权位置信息',
				showCancel: false,
				confirmText: '授权',
				success: (res) => {
					if (res.confirm) {
						uni.openSetting({
							success(res) {
								uni.getSetting({
									success(re) {
										if (res.authSetting['scope.userLocation']) {
											setLocationMap((locate) => {
												successCallback &&
													successCallback(locate)
											})
										}
									},
									fail(f) {
										store.commit('setLocateInformation', {});
										console.log(f, '====fali loaction')
										uni.showToast({
											title: '请开启手机获取位置功能权限',
											duration: 3000,
											icon: 'none'
										});
									}
								})

							}
						})
					}
				}
			})
		}
	});
}
// // 已授权地理位置
export function setLocationMap(callback) {
	uni.getLocation({
		type: 'gcj02',
		success(res) {
			store.commit('setLocateInformation', {
				latitude: res.latitude,
				longitude: res.longitude
			});
			callback && callback(res)
		},
		fail(f) {
			console.log(f, '====fali loaction')
			store.commit('setLocateInformation', {});
			uni.showToast({
				title: '请开启手机获取位置功能权限',
				duration: 3000,
				icon: 'none'
			});
		}
	})
}

/**
 * 经纬度 换 位置描述 (逆地址解析)
 **/
export function reverseGeocoder(longitude, latitude, callback) {
	return new Promise((resolve, reject) => {
		const url =
			`https://apis.map.qq.com/ws/geocoder/v1/?key=${settings.tencentLocationKey}&location=${latitude},${longitude}`
		uni.request({
			url,
			success: (res) => {
				if (res.data.status == 0) {
					console.log('地址解析请求成功', res)
					var result = res.data.result
					store.commit('setLoactionAddress', {
						...result,
						...{
							province: result.ad_info.province,
							city: result.ad_info.city,
							area: result.ad_info.district,
							address: result.formatted_addresses ? result
								.formatted_addresses.recommend : result.address,
							default: result.ad_info.district,
						}
					})
					resolve(res.data)
					callback && callback(result)
				} else {
					console.log('请求失败', res)
					reject(res.data.message)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}
/**
 * 地址解析（地址转坐标）
 **/
export function reverseAddress(address, call) {
	const url =
		`https://apis.map.qq.com/ws/geocoder/v1/?key=${tencentLocationKey}&address=${address}`
	return new Promise((resolve, reject) => {
		uni.request({
			url,
			success: (res) => {
				if (res.data.status == 0) {
					console.log('地址转坐标成功', res)
					call(res.data)
					resolve(res.data)
				} else {
					console.log('地址转坐标失败', res)
					reject(res.data.message)
				}
			},
			fail: (err) => {
				reject(err)
			}
		})
	})
}


export function uploadFile(filePath, callback) {

	uni.uploadFile({
		url: settings.baseUrl + '/Upload/image',
		filePath: filePath,
		name: 'file',
		header: {
			'token': uni.getStorageSync('token')
		},
		formData: {
			...shaParams({
				file: filePath
			}),
		},
		success: (res) => {
			let data = JSON.parse(res.data);
			console.log(data, 'uploadFile')
			callback && callback(data)
		}
	});
}